Inheritance allows one class (child class) to inherit the properties and methods of another class (parent class). It supports reusability and method overriding.
// Example of Single Inheritance
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
The 'super' keyword refers to the immediate parent class. It is used to access parent class methods, constructors, and variables.
class Parent {
void display() {
System.out.println("Parent class method");
}
}
class Child extends Parent {
void display() {
super.display(); // Calls parent class method
System.out.println("Child class method");
}
}
Method overriding occurs when a child class provides its own implementation of a method already defined in its parent class.
class Vehicle {
void run() {
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle {
void run() {
System.out.println("Bike is running safely");
}
}
In method overriding, a child class can return a subtype of the parent class's return type. This is called a covariant return type.
class Parent {
Parent get() {
return this;
}
}
class Child extends Parent {
@Override
Child get() { // Covariant return type
return this;
}
}
An abstract class cannot be instantiated directly. It can have abstract methods (methods without a body) and concrete methods.
abstract class Shape {
abstract void draw(); // Abstract method (no body)
void message() {
System.out.println("This is a shape");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}